package br.com.bolsamovel;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {
	private static Pattern REGEX_PONTOS_EM_SEQUENCIA = Pattern.compile("\\.\\.", Pattern.CASE_INSENSITIVE|Pattern.DOTALL);

	public static String emptyAsNull(String s){
		if(s == null){
			return null;
		}
		
		s = s.trim();
		return s.length() == 0 ? null : s;
	}
	
	public static double normalizeAsNumber(String s){
		s = s.replaceAll(",", ".").replaceAll("[^0123456789.,]", "");
		
		StringBuffer b = new StringBuffer();
		b.append(s);
		
		Matcher m = REGEX_PONTOS_EM_SEQUENCIA.matcher(b);
		
		while(m.find()){
			b.replace(m.start(), m.end(), ".");
			m.reset(b);
		}

		return b.toString().length() > 0 ? Double.valueOf(b.toString()) : 0;
	}
}
